package lzy.controller;

import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lzy.entity.GinsengTraceability;
import lzy.entity.User;
import lzy.service.GinsengTraceabilityService;
import org.springframework.beans.factory.annotation.Autowired;

@Controller
public class ConsumerController {
    @Autowired
    private GinsengTraceabilityService ginsengTraceabilityService;
    
    // 临时内部类用于演示，实际开发请替换为正式实体
    public static class Messages {
        public String cropType;
        public String dateTime;
        public String location;
        public Integer area;
        public Integer avgTemp;
        public Integer maxTemp;
        public Integer minTemp;
        public String airQuality;
        public String pm25;
        public String humidity;
        public String pressure;
        public String uvIndex;
        public String soilPh;
        public String soilMoisture;
        public String fertilizeRecord;
        public String fieldOperation;
        public String pestWarning;
        public String rainWarning;
    }
    
    // 消费者首页
    @GetMapping("/consumer/index")
    public String consumerIndex(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        return "consumer/consumer_index";
    }

    // 消费者消息中心
    @GetMapping("/consumer/message")
    public String consumerMessage(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // 未登录处理
            return "redirect:/login";
        }
        String consumerId = user.getUsername();
        // TODO: 替换为实际的消息Service
        List<Messages> messages = new ArrayList<>();
        // 示例：messages = messageService.findMsgByID(consumerId);
        model.addAttribute("messages", messages);
        return "consumer/consumer_message";
    }

    // 消费者个人中心
    @GetMapping("/consumer/personal")
    public String consumerPersonal(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // 未登录处理
            return "redirect:/login";
        }
        String consumerId = user.getUsername();
        // TODO: 替换为实际的用户Service
        String consumerName = user.getRealName(); // 假设User有realName字段
        model.addAttribute("consumerId", consumerId);
        model.addAttribute("consumerName", consumerName);
        return "consumer/consumer_personal";
    }

    @GetMapping("/consumer/personal/edit")
    public String editPersonal(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        model.addAttribute("user", user);
        return "consumer/edit_personal";
    }

    @PostMapping("/consumer/personal/edit")
    public String updatePersonal(@ModelAttribute User updatedUser, HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        // TODO: 调用userService更新数据库
        // userService.updateUserInfo(updatedUser);
        // 更新session
        session.setAttribute("user", updatedUser);
        redirectAttributes.addFlashAttribute("success", "信息修改成功！");
        return "redirect:/consumer/personal";
    }

    @GetMapping("/consumer/personal/password")
    public String changePasswordPage() {
        return "consumer/change_password";
    }

    @PostMapping("/consumer/personal/password")
    public String changePassword(@RequestParam String oldPassword,
                                @RequestParam String newPassword,
                                @RequestParam String confirmPassword,
                                HttpSession session,
                                RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        // TODO: 校验原密码，更新新密码
        // if (!userService.authenticate(user.getUsername(), oldPassword)) { ... }
        // userService.updatePassword(user.getId(), newPassword);
        redirectAttributes.addFlashAttribute("success", "密码修改成功！");
        return "redirect:/consumer/personal";
    }
    
    // 溯源码查询页面
    @GetMapping("/consumer/traceability")
    public String traceabilityPage() {
        return "consumer/traceability";
    }
    
    // 溯源码查询接口
    @PostMapping("/consumer/traceability/query")
    @ResponseBody
    public Map<String, Object> queryTraceability(@RequestParam String traceCode) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            GinsengTraceability trace = ginsengTraceabilityService.findByTraceCode(traceCode);
            if (trace != null) {
                result.put("success", true);
                result.put("data", trace);
            } else {
                result.put("success", false);
                result.put("message", "未找到该溯源码的相关信息");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败：" + e.getMessage());
        }
        
        return result;
    }
    
    // 消费者首页搜索接口
    @PostMapping("/consumer/search")
    @ResponseBody
    public Map<String, Object> consumerSearch(@RequestParam String keyword) {
        Map<String, Object> result = new HashMap<>();
        List<GinsengTraceability> searchResults = new ArrayList<>();
        
        try {
            // 尝试通过溯源码查询
            GinsengTraceability traceByCode = ginsengTraceabilityService.findByTraceCode(keyword);
            if (traceByCode != null) {
                searchResults.add(traceByCode);
            }
            
            // 尝试通过批次号查询
            List<GinsengTraceability> traceByBatch = ginsengTraceabilityService.findByBatchNo(keyword);
            if (traceByBatch != null && !traceByBatch.isEmpty()) {
                // 合并结果，避免重复
                for (GinsengTraceability trace : traceByBatch) {
                    if (!searchResults.stream().anyMatch(t -> t.getTraceCode().equals(trace.getTraceCode()))) {
                        searchResults.add(trace);
                    }
                }
            }
            
            // 如果没有结果，查询所有记录（简单实现，实际可以添加更复杂的搜索逻辑）
            if (searchResults.isEmpty()) {
                List<GinsengTraceability> allRecords = ginsengTraceabilityService.findAll();
                // 简单过滤：检查关键词是否在产品名称或品种中
                for (GinsengTraceability trace : allRecords) {
                    if ((trace.getProductName() != null && trace.getProductName().contains(keyword)) ||
                        (trace.getVariety() != null && trace.getVariety().contains(keyword)) ||
                        (trace.getOrigin() != null && trace.getOrigin().contains(keyword))) {
                        searchResults.add(trace);
                    }
                }
            }
            
            result.put("success", true);
            result.put("data", searchResults);
            result.put("count", searchResults.size());
            
            if (searchResults.isEmpty()) {
                result.put("message", "未找到相关信息");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "搜索失败：" + e.getMessage());
        }
        
        return result;
    }
}